﻿//------------------------------------------------------------------
// System Name:    smsGateway
// Component:      Data
// Create by:      Evans Liao (evansl@wicresoft.com)
// Create Date:    2011-01-03
//------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SMS.Common;

namespace Wicresoft.SMS.Data
{
    public class UserService : IUserService
    {
        private IConnectStringProvider icsp;

        public UserService(IConnectStringProvider _icsp)
        {
            this.icsp = _icsp;
        }

        public User GetUserItemByCIL(string cil)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var user = dbacc.User.FirstOrDefault(a => a.CIL == cil);
                if (user != null)
                {
                    user.Role.Load();
                    var a = user.Department;
                }
                return user;
            }
        }


        public bool CreateOrUpdateUser(User user)
        {
            try
            {
                using (var dbacc = new Entities(icsp.ConnectionString))
                {
                    var temp = dbacc.User.FirstOrDefault(a => a.CIL == user.CIL);
                    if (temp != null)
                    {
                        temp.NameCN = user.NameCN;
                        temp.NameEN = user.NameEN;
                        temp.Email = user.Email;
                        temp.IsActive = user.IsActive;
                        temp.DepartmentID = user.DepartmentID;
                        temp.Mobile = user.Mobile;
                        temp.DeptName = user.DeptName;
                        temp.CSL = user.CSL;
                    }
                    else
                    {
                        Role role = dbacc.Role.FirstOrDefault(a => a.RoleName == "User");
                        if (role != null)
                            user.Role.Add(role);
                        dbacc.AddToUser(user);
                    }
                    dbacc.SaveChanges();

                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        public bool AskForActive(int id, string url)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var admins = dbacc.User.Where(u => u.Role.FirstOrDefault(r => r.RoleName == "Admin") != null);
                var user = dbacc.User.FirstOrDefault(a => a.UserID == id);
                if (user == null)
                    return false;
                user.IsActive = 2;
                dbacc.SaveChanges();
                Email email = CreateEmail(user, url);
                foreach (var item in admins)
                {
                    if (email.To == null)
                        email.To = "";
                    email.To += item.Email + ";";
                }

                List<Email> list = new List<Email>();
                list.Add(email);
                IEmailDataAccess ieda = new sqlEmailDataAccess(icsp);
                return ieda.SendEmail(list);
            }
        }

        private Email CreateEmail(User user, string _url)
        {
            Email email = new Email();
            email.Subject = "Ask for active gateway account";
            email.UserID = user.UserID;

            string mainemail = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                              "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                              "<head>" +
                              "<title>FailedNotification.htm</title>" +
                              "<style type=\"text/css\">" +
                              ".style2leftcallcolor: #666666;font-size: medium;rightcall" +
                              ".style3leftcallfont-size: small;color: #333333;rightcall" +
                              "pleftcallmargin:6px;font-size:14px;rightcall" +
                              ".style4leftcallfont-family: \"Khmer UI\";font-size: 40px;rightcall" +
                              "</style>" +
                              "</head>" +
                              "<body style=\"text-align: left\">" +
                              "<p>亲爱的管理员:</p>" +
                              "<p>&nbsp;</p>" +
                              "<p>用户 {0} 希望获得SMS网关的使用权限：</p>" +
                              "<p> 请点击<a href=\"{1}\">创建用户</a>用以批准该用户的请求。</p>" +
                              "<p>&nbsp;</p>" +
                              "<p>如果您的电子邮件程序不支持点击“创建用户”，请将此链接粘贴至您的网络浏览器中</p>" +
                              "<p>{1}</p>" +
                              "<p>此邮件为系统自动发送，请勿回复，谢谢合作。</p>" +
                              "<p>&nbsp;</p>" +
                              "<p class=\"style2\">上海贝尔短信平台系统</p>" +
                              "<p class=\"style2\">{2}</p>" +
                              "</body>" +
                              "</html>";
            string url = _url + "manage/users/create?id=" + user.UserID;
            email.Content = string.Format(mainemail, user.NameEN, url, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            return email;
        }


        public User GetUserItemByID(int id)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var user = dbacc.User.FirstOrDefault(a => a.UserID == id);
                if (user != null)
                {
                    user.Role.Load();
                    var a = user.Department;
                }
                return user;
            }
        }


        public bool CreateOrUpdateUser(C_evw_Employee[] users, bool isactive, bool isadmin)
        {
            if (users == null)
                return false;
            if (users.Count() == 0)
                return false;
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                string rolename = isadmin ? "Admin" : "User";
                var role = dbacc.Role.FirstOrDefault(r => r.RoleName == rolename);
                foreach (var item in users)
                {
                    var temp = dbacc.User.FirstOrDefault(a => a.CIL == item.CILX500);
                    if (temp == null)
                    {
                        User newuser = new User();
                        newuser.CIL = item.CILX500;
                        newuser.NameCN = item.NameCN;
                        newuser.NameEN = item.NameEN;
                        newuser.Email = item.Email;
                        newuser.IsActive = isactive ? 4 : 3;
                        newuser.DepartmentID = isadmin ? 1 : 2;
                        newuser.DeptName = item.DeptName;
                        newuser.CSL = item.NTacount;
                        newuser.Role.Add(role);
                        dbacc.AddToUser(newuser);
                    }
                    else
                    {
                        temp.CIL = item.CILX500;
                        temp.NameCN = item.NameCN;
                        temp.NameEN = item.NameEN;
                        temp.Email = item.Email;
                        temp.DeptName = item.DeptName;
                        temp.IsActive = isactive ? 4 : 3;
                        temp.DepartmentID = isadmin ? 1 : 2;
                        temp.CSL = item.NTacount;
                        temp.Role.Clear();
                        temp.Role.Add(role);
                    }
                }
                dbacc.SaveChanges();
            }
            return true;
        }
        
        public List<UserInfo> GetAllUsers(bool iswithunactive)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
               // int state = iswithunactive ? 3 : 4;
                var users = from a in dbacc.User
                            // where a.IsActive >= state
                             select a;
                if (users != null)
                {
                    List<UserInfo> list = new List<UserInfo>();
                    foreach (var item in users)
                    {
                        UserInfo ui = new UserInfo();
                        ui.ID = item.UserID;
                        ui.CIL = item.CIL;
                        ui.NameEN = item.NameEN;
                        ui.Email = item.Email;
                        ui.IsActive = GetStateString(item.IsActive);// == 4 ? "True" : "False";
                        ui.DeptName = item.DeptName;
                        list.Add(ui);
                    }
                    return list;
                }
                else
                    return null;
            }
        }

        public string GetStateString(int state)
        {
            switch (state)
            {
                case 0:
                    return "New";
                case 1:
                    return "Refused";
                case 2:
                    return "Applying";
                case 3:
                    return "Disabled";
                case 4:
                    return "Enabled";
                default:
                    return "";
            }
        }

        public List<UserInfo> GetAllUsers(int index, int max, string key)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var users = (from a in dbacc.User
                             where a.CIL.Contains(key) || a.NameEN.Contains(key) || a.NameCN.Contains(key)
                             where a.IsActive > 2
                             orderby a.UserID
                             select a).Skip((index - 1) * max).Take(max);
                if (users != null)
                {
                    List<UserInfo> list = new List<UserInfo>();
                    foreach (var item in users)
                    {
                        UserInfo ui = new UserInfo();
                        ui.ID = item.UserID;
                        ui.CIL = item.CIL;
                        ui.NameEN = item.NameEN;
                        ui.Email = item.Email;
                        ui.IsActive = item.IsActive == 4 ? "True" : "False";
                        list.Add(ui);
                    }
                    return list;
                }
                else
                    return null;
            }
        }

        public int GetPageCount(int max, string key)
        {
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                var users = from a in dbacc.User
                            where a.CIL.Contains(key) || a.NameEN.Contains(key) || a.NameCN.Contains(key)
                            where a.IsActive == 3 || a.IsActive == 4
                            orderby a.UserID
                            select a;
                int count = (users.Count() + (max - 1)) / max;
                return count;
            }
        }


        public bool ActiveUsers(bool isactive, string[] userids)
        {
            if (userids == null)
                return false;
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                foreach (var item in userids)
                {
                    int id = Convert.ToInt32(item);
                    var user = dbacc.User.FirstOrDefault(u => u.UserID == id);
                    if (user != null)
                    {
                        user.IsActive = isactive ? 4 : 3;
                    }
                }
                dbacc.SaveChanges();
                return true;
            }
        }


        public List<UserInfo> GetAllUsers(int index, int max, string key, bool isPending)
        {
            if (isPending)
            {
                using (var dbacc = new Entities(icsp.ConnectionString))
                {
                    var users = (from a in dbacc.User
                                 where a.CIL.Contains(key) || a.NameEN.Contains(key) || a.NameCN.Contains(key)
                                 where a.IsActive == 2
                                 orderby a.UserID
                                 select a).Skip((index - 1) * max).Take(max);
                    if (users != null)
                    {
                        List<UserInfo> list = new List<UserInfo>();
                        foreach (var item in users)
                        {
                            UserInfo ui = new UserInfo();
                            ui.ID = item.UserID;
                            ui.CIL = item.CIL;
                            ui.NameEN = item.NameEN;
                            ui.Email = item.Email;
                            ui.IsActive = item.IsActive == 2 ? "True" : "False";
                            list.Add(ui);
                        }
                        return list;
                    }
                    else
                        return null;
                }
            }
            else
            {
                return GetAllUsers(index, max, key);
            }
        }


        public int GetPageCount(int max, string key, bool isPending)
        {
            if (isPending)
            {
                using (var dbacc = new Entities(icsp.ConnectionString))
                {
                    var users = from a in dbacc.User
                                where a.CIL.Contains(key) || a.NameEN.Contains(key) || a.NameCN.Contains(key)
                                where a.IsActive == 2
                                orderby a.UserID
                                select a;
                    int count = (users.Count() + (max - 1)) / max;
                    return count;
                }
            }
            else
            {
                return GetPageCount(max, key);
            }
        }


        public bool AllowUsers(bool isallow, string[] userids)
        {
            if (userids == null)
                return false;
            using (var dbacc = new Entities(icsp.ConnectionString))
            {
                foreach (var item in userids)
                {
                    int id = Convert.ToInt32(item);
                    var user = dbacc.User.FirstOrDefault(u => u.UserID == id);
                    if (user != null)
                    {
                        user.IsActive = isallow ? 4 : 1;
                    }
                }
                dbacc.SaveChanges();
                return true;
            }
        }


    }
}
